package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description: 定时处理订单状态
 * @Author: Zonghe Wang
 * @Date: 2025/1/26 12:36
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单的方法
     */
    @Scheduled(cron = "0 * * * * ?") // 每分钟触发一次
    public void processTimeOutOrders() {
        log.info("处理超时订单:{}", LocalDateTime.now());
        // select * from orders where pay_status = ? and order_time < ?(currentTime - 15min)
        List<Orders> outTimeOrders =  orderMapper.selectOutTime(Orders.PENDING_PAYMENT , LocalDateTime.now().plusMinutes(-15));

        if (outTimeOrders != null && !outTimeOrders.isEmpty()) {
            for (Orders o : outTimeOrders) {
                o.setStatus(Orders.CANCELLED);
                o.setCancelTime(LocalDateTime.now());
                o.setCancelReason("订单超时，自动取消");
                orderMapper.update(o);
            }
        }

    }

    /**
     * 处理一直派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ?") //每天凌晨1点
    public void processDeliveryOrders() {
        log.info("处理一直派送中的订单:{}", LocalDateTime.now());
        List<Orders> outTimeOrders =  orderMapper.selectOutTime(Orders.DELIVERY_IN_PROGRESS , LocalDateTime.now().plusHours(-1));

        if (outTimeOrders != null && !outTimeOrders.isEmpty()) {
            for (Orders o : outTimeOrders) {
                o.setStatus(Orders.COMPLETED);
                o.setEstimatedDeliveryTime(LocalDateTime.now());
                orderMapper.update(o);
            }
        }
    }


}
